<template>
  <div class="pmjl-container" id="capture-area">
    <table class="pmjl-table" border="1">
      <caption>压力监测图</caption>
      <colgroup>
        <col width="4%"/>
        <col width="20%"/>
        <col width="20%"/>
        <col width="20%"/>
        <col width="36%"/>
      </colgroup>

      <tr style="height: 5rem;text-align: center;vertical-align: bottom;">
        <td>深度</td>
        <td>ROP</td>
        <td>
          <div class="c-red">C_isotope</div>
          <hr class="c-red"/>
          <div class="c-red both-clear">
            <span class="pull-left">-60</span>
            <span class="pull-right">0</span>
          </div>
          <div>Coco3</div>
        </td>
        <td>
          <div class="c-red">C1</div>
          <hr class="c-red"/>
          <div class="c-red both-clear">
            <span class="pull-left">0.1</span>
            <span class="pull-right">10</span>
          </div>
          <div>TG<small>25</small></div>
        </td>
        <td>
          <p>ECD</p>
        </td>
      </tr>
      <tr style="height: 1rem;">
        <td>
          <span class="pull-left">0</span>
          <span class="pull-right">15</span>
        </td>
        <td>
          <span class="pull-left">0</span>
          <span class="pull-right">20</span>
        </td>
        <td>
          <span class="pull-left">0.1</span>
          <span class="pull-right">10</span>
        </td>
        <td>
          <span class="pull-left">0.1</span>
          <span class="pull-right">10</span>
        </td>
      </tr>
      <tr class="tr-chart">
        <td>
          <div id="chart0" class="chart-container"></div>
        </td>
        <td>
          <div id="chart1" class="chart-container"></div>
        </td>
        <td>
          <div id="chart2" class="chart-container"></div>
        </td>
        <td>
          <div id="chart3" class="chart-container"></div>
        </td>
        <td>
          <div id="chart4" class="chart-container"></div>
        </td>
      </tr>
    </table>
    <!-- <div id="chart" style="width: 100%;height:500px;"></div> -->
    <div class="pmjl-container">
      <el-tooltip content="配置曲线样式" placement="top">
        <el-button
            type="primary"
            icon="el-icon-setting"
            circle
            class="style-editor-button"
            @click="styleDrawerVisible = true"
            v-if="!isCapturing && map.well_id"
        ></el-button>
      </el-tooltip>

      <el-drawer
          title="曲线样式配置"
          :visible.sync="styleDrawerVisible"
          direction="rtl"
          size="450px">

        <div class="drawer-body">
          <el-form label-width="80px" size="small">
            <el-form-item
                v-for="(style, seriesName) in seriesStyles"
                :key="seriesName"
                :label="seriesName.toUpperCase()">

              <div class="style-config-row">
                <el-color-picker v-model="style.color" show-alpha class="style-config-item"></el-color-picker>
                <el-input-number v-model="style.width" :min="1" :max="10" label="线宽"
                                 class="style-config-item"></el-input-number>
                <el-select v-model="style.type" placeholder="请选择线型" class="style-config-item">
                  <el-option label="实线" value="solid"></el-option>
                  <el-option label="虚线" value="dashed"></el-option>
                  <el-option label="点线" value="dotted"></el-option>
                </el-select>
              </div>

            </el-form-item>
          </el-form>
        </div>

        <div class="drawer-footer">
          <el-button @click="resetStyles">恢复默认</el-button>
          <el-button type="primary" @click="applyStyles">应用并关闭</el-button>
        </div>
      </el-drawer>

      <table class="pmjl-table" border="1">
      </table>

    </div>
    <el-tooltip content="保存为长图" placement="top">
      <el-button
          type="success"
          icon="el-icon-camera"
          circle
          class="save-image-button"
          @click="saveAsLongImage"
          v-if="!isCapturing"
      ></el-button>
    </el-tooltip>
    <el-tooltip content="导出报告" placement="top">
      <el-button
          type="primary"
          icon="el-icon-download"
          circle
          class="export-report-button"
          @click="exportReport"
          v-if="!isCapturing"
      ></el-button>
    </el-tooltip>
  </div>
</template>

<script>
import api from '@/api/api.js';
import html2canvas from 'html2canvas';

export default {
  name: 'KxylEchartsBowers',
  mounted() {
    // 保存初始样式为默认值，以便后续可以重置
    this.defaultSeriesStyles = JSON.parse(JSON.stringify(this.seriesStyles));
  },
  data() {
    return {
      isCapturing: false,//是否在截图中
      originalDataZoomState: null,//用来储存截图之前的dataZoom配置
      drawMode: false, // 是否开启绘制模式
      isDrawing: false,
      drawStartPoint: null,
      drawEndPoint: null,
      currentDrawingChart: null,
      startPoint: null,//趋势线的开始坐标
      endPoint: null,//趋势线的结束坐标
      k: null,//趋势线的斜率
      b: null,//趋势线的截距
      // 添加用于存储趋势线的数据
      trendLines: {
        chart1: [],
        chart2: [],
        chart3: [],
        chart4: []
      },
      chart0: null,
      chart1: null,
      chart2: null,
      chart3: null,
      chart4: null,
      echartsData: [],
      map: {
        well_id: '',
        n: '',
        Vp: '',
        Vs: '',
        h_rect: 0,
        H_rect: 0,
        UCS: '',
        o: '',
        v0: '',
        a: '',
        b: ''
      },
      styleDrawerVisible: false, // 控制抽屉显示
      defaultSeriesStyles: {}, // 用于保存默认样式
      seriesStyles: {
        nhg: {color: '#ffc107', width: 2, type: 'solid'},
        obg: {color: '#343a40', width: 2, type: 'solid'},
        dt: {color: '#17a2b8', width: 2, type: 'solid'},
        pp: {color: '#ff2f00', width: 2, type: 'solid'},
        pc: {color: '#28a745', width: 2, type: 'solid'},
        pf: {color: '#3556dc', width: 2, type: 'solid'},
      },
      showStyleEditor: false, // 控制样式编辑器UI的显示/隐藏
    }
  },
  methods: {
    initialize() {
      this.chart0 = this.$echarts.init(document.getElementById('chart0'));
      this.chart1 = this.$echarts.init(document.getElementById('chart1'));
      this.chart2 = this.$echarts.init(document.getElementById('chart2'));
      this.chart3 = this.$echarts.init(document.getElementById('chart3'));
      this.chart4 = this.$echarts.init(document.getElementById('chart4'));

      // 为 Chart4 绑定点击事件，它对应多个序列
      this.chart4.on('click', (params) => {
        this.handleChartClick(params, this.chart4, ['pp', 'pc', 'pf']);
      });
      // 设置图表联动
      this.setupChartLinkage();
      this.retrieveEchartsData3();
    },
    initialize1() {
      this.chart0 = this.$echarts.init(document.getElementById('chart0'));
      this.chart1 = this.$echarts.init(document.getElementById('chart1'));
      this.chart2 = this.$echarts.init(document.getElementById('chart2'));
      this.chart3 = this.$echarts.init(document.getElementById('chart3'));
      this.chart4 = this.$echarts.init(document.getElementById('chart4'));

      // 为 Chart4 绑定点击事件，它对应多个序列
      this.chart4.on('click', (params) => {
        this.handleChartClick(params, this.chart4, ['pp', 'pc', 'pf']);
      });

      // 设置图表联动
      this.setupChartLinkage();
      this.retrieveEchartsData2();
    },
    setupChartLinkage() {
      //设置图表联动，共享y轴缩放
      const charts = [this.chart0, this.chart1, this.chart2, this.chart3, this.chart4];

      charts.forEach((chart, index) => {
        chart.on('dataZoom', (params) => {
          //当一个图表发生缩放时，同步到其他图表
          const zoomInfo = chart.getOption().dataZoom[0];

          charts.forEach((otherChart, otherIndex) => {
            if (index !== otherIndex) {
              otherChart.setOption({
                dataZoom: [{
                  start: zoomInfo.start,
                  end: zoomInfo.end
                }]
              });
            }
          });
        });
      });
    },
    retrieveEchartsData() {
      api.post('/kxyl/bbb', this.map)
          .then(response => {
            // 处理成功的响应
            this.echartsData = response.data.list || [];
            return this.echartsData;
          }).then(this.renderEcharts).catch(() => {
        this.echartsData = [];
      })
    }, retrieveEchartsData1() {
      api.post('/kxyl/ccc', this.map)
          .then(response => {
            // 处理成功的响应
            this.echartsData = response.data.list || [];
            return this.echartsData;
          }).then(this.renderEcharts).catch(() => {
        this.echartsData = [];
      })
    }, retrieveEchartsData2() {
      api.post('/kxyl/ddd', this.map)
          .then(response => {
            // 处理成功的响应
            this.echartsData = response.data.list || [];
            return this.echartsData;
          }).then(this.renderEcharts).catch(() => {
        this.echartsData = [];
      })
    }, retrieveEchartsData3() {
      api.post('/bowers/getBowersPP', this.map)
          .then(response => {
            // 处理成功的响应
            this.echartsData = response.data.list || [];
            return this.echartsData;
          }).then(this.renderEcharts).catch(() => {
        this.echartsData = [];
      })
    }
    ,
    renderEcharts() {
      const data1 = []; // pp数据
      const data2 = []; // pc数据
      const data3 = []; // pf数据
      const data4Nhg = []; // nhg数据
      const data4Obg = []; // obg数据
      const dataDt = []; // dt数据

      this.echartsData.forEach(item => {
        item.depth = Number(item.depth);
        // [压力值, 深度值] 坐标对
        data1.push([item.pp, item.depth, item.id]);
        data2.push([item.pc, item.depth, item.id]);
        data3.push([item.pf, item.depth, item.id]);
        data4Nhg.push([item.nhg, item.depth, item.id]);
        data4Obg.push([item.obg, item.depth, item.id]);
        dataDt.push([item.dt, item.depth, item.id]);
      });
      this.renderChart0(data1);
      this.renderChart1(data4Nhg);
      this.renderChart2(data4Obg);
      this.renderChart3(dataDt);
      this.renderChart4(data1, data2, data3);
    },
    renderChart0(depthData) {
      // 从传入的数据中提取深度值数组
      const depths = depthData.map(item => item[1]);
      const option = {
        grid: {
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          containLabel: true
        },
        //只显示y轴
        yAxis: {
          type: 'value',
          inverse: true,
          min: Math.min(...depths) || 1000,
          max: Math.max(...depths) || 4000,
          // 确保显示y轴刻度标签
          axisLabel: {
            show: true
          },
        },
        // 不显示x轴
        xAxis: {
          show: false
        },
        // 添加dataZoom配置，使chart0可以跟随其他图表缩放
        dataZoom: [
          {
            type: 'inside',
            zoomOnMouseWheel: 'ctrl',
            start: 0,
            end: 100,
            yAxisIndex: 0,
            moveOnMouseWheel: true
          }
        ],
        // 不显示任何系列数据
        series: []
      }
      this.chart0.setOption(option);
    },
    renderChart1(ds) {
      const nhgStyle = this.seriesStyles.nhg; // 获取 nhg 的样式配置
      const option = {
        legend: {
          data: ['nhg']
        },
        grid: {
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line',
            axis: 'y'
          },
        },
        yAxis: {
          type: 'value',
          inverse: true,
          min: 1000,
          max: 4000,
          axisLabel: {
            show: false
          }
        },
        dataZoom: [
          {
            type: 'inside',
            zoomOnMouseWheel: 'ctrl',
            start: 0,
            end: 100,
            show: true,
            yAxisIndex: 0,
            moveOnMouseWheel: true
          }
        ],
        xAxis: {
          type: 'value',
          axisLine: {
            show: true
          }
        },
        series: [
          {
            name: 'nhg',
            type: 'line', // 这里设置曲线的类型为'line'，你也可以设置为'area'来创建面积图等
            data: ds,
            encode: {tooltip: 0},
            triggerLineEvent: true,
            symbol: 'none',
            lineStyle: {
              color: nhgStyle.color,
              width: nhgStyle.width,
              type: nhgStyle.type
            },
            itemStyle: {
              color: nhgStyle.color,
            },
          }
        ]
      };
      this.chart1.setOption(option);
    },
    renderChart2(ds) {
      const obgStyle = this.seriesStyles.obg; // 获取 obg 的样式配置
      const option = {
        legend: {
          data: ['obg'],
        },
        grid: {
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line',
            axis: 'y',
          },
        },
        yAxis: {
          type: 'value',
          inverse: true,
          min: 1000,
          max: 4000,
          axisLabel: {
            show: false
          }
        },
        dataZoom: [
          {
            type: 'inside',
            zoomOnMouseWheel: 'ctrl',
            show: false,
            start: 0,
            end: 100,
            yAxisIndex: 0,
            moveOnMouseWheel: true
          }
        ],
        xAxis: {
          type: 'value',
          axisLine: {
            show: true
          }
        },
        series: [
          {
            name: 'obg',
            type: 'line', // 这里设置曲线的类型为'line'，你也可以设置为'area'来创建面积图等
            data: ds,
            encode: {tooltip: 0},
            triggerLineEvent: true,
            symbol: 'none',
            lineStyle: {
              color: obgStyle.color,
              width: obgStyle.width,
              type: obgStyle.type
            },
            itemStyle: {
              color: obgStyle.color,
            },
          }
        ]
      };
      this.chart2.setOption(option);
    },
    renderChart3(ds) {
      const dtStyle = this.seriesStyles.dt; // 获取 dt 的样式配置
      const option = {
        legend: {
          data: ['dt'],
        },
        grid: {
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            axis: 'y'
          },
        },
        yAxis: {
          type: 'value',
          inverse: true,
          min: 1000,
          max: 4000,
          axisLabel: {
            show: false
          }
        },
        dataZoom: [
          {
            type: 'inside',
            zoomOnMouseWheel: 'ctrl',
            show: false,
            start: 0,
            end: 100,
            yAxisIndex: 0,
            moveOnMouseWheel: true
          }
        ],
        xAxis: {
          type: 'value',
          axisLine: {
            show: true
          }
        },
        series: [
          {
            name: 'dt',
            type: 'line', // 这里设置曲线的类型为'line'，你也可以设置为'area'来创建面积图等
            smooth: true,
            data: ds,
            encode: {tooltip: 0},
            triggerLineEvent: true,
            symbol: 'none',
            lineStyle: {
              color: dtStyle.color,
              width: dtStyle.width,
              type: dtStyle.type
            },
            itemStyle: {
              color: dtStyle.color, // 图例图标颜色与系列颜色一致
            },
          }
        ]
      };
      this.chart3.setOption(option);
    },
    renderChart4(ds, ps, obg) {
      const pfStyle = this.seriesStyles.pf;
      const ppStyle = this.seriesStyles.pp;
      const pcStyle = this.seriesStyles.pc;
      const option = {
        legend: {
          data: ['pc', 'pp', 'pf']
        },
        grid: {
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line',
            axis: 'y'
          },
        },
        yAxis: {
          type: 'value',
          inverse: true,
          min: 1000,
          max: 4000,
          axisLabel: {
            show: false
          }
        },
        dataZoom: [
          {
            type: 'inside',
            zoomOnMouseWheel: 'ctrl',
            show: false,
            start: 0,
            end: 100,
            yAxisIndex: 0,
            moveOnMouseWheel: true
          }
        ],
        xAxis: {
          type: 'value',
          axisLine: {
            show: true
          }
        },
        series: [
          {
            name: 'pp',
            type: 'line', // 这里设置曲线的类型为'line'，你也可以设置为'area'来创建面积图等
            smooth: true,
            data: ds,
            encode: {tooltip: 0},
            triggerLineEvent: true,
            symbol: 'none',
            lineStyle: {
              color: ppStyle.color,
              width: ppStyle.width,
              type: ppStyle.type
            },
            itemStyle: {
              color: ppStyle.color,
            }
          },
          {
            name: 'pc',
            type: 'line', // 这里设置曲线的类型为'line'，你也可以设置为'area'来创建面积图等
            smooth: true,
            data: ps,
            encode: {tooltip: 0},
            triggerLineEvent: true,
            symbol: 'none',
            lineStyle: {
              color: pcStyle.color,
              width: pcStyle.width,
              type: pcStyle.type
            },
            itemStyle: {
              color: pcStyle.color,
            }
          },
          {
            name: 'pf',
            type: 'line', // 这里设置曲线的类型为'line'，你也可以设置为'area'来创建面积图等
            smooth: true,
            data: obg,
            encode: {tooltip: 0},
            triggerLineEvent: true,
            symbol: 'none',
            lineStyle: {
              color: pfStyle.color,
              width: pfStyle.width,
              type: pfStyle.type
            },
            itemStyle: {
              color: pfStyle.color,
            },
          }
        ]
      };
      this.chart4.setOption(option);
    },
    // 样式确认按钮
    applyStyles() {
      this.renderEcharts();
      this.styleDrawerVisible = false;
    },
    //样式重置按钮
    resetStyles() {
      this.seriesStyles = JSON.parse(JSON.stringify(this.defaultSeriesStyles));
      this.renderEcharts();
      this.$message.success('已恢复默认样式');
    },
    // 点击数据点事件
    handleChartClick(params, chartInstance, seriesNames) {
      // 如果处于绘制模式，则不执行数据点编辑逻辑
      if (this.drawMode) {
        return;
      }
      console.log("params:", params);
      // 1. 获取点击的像素坐标，并转换为该图表的逻辑坐标（深度）
      const pointInPixel = [params.event.offsetX, params.event.offsetY];
      if (!chartInstance.containPixel('grid', pointInPixel)) return; // 点击在网格之外，则忽略

      const pointInGrid = chartInstance.convertFromPixel('grid', pointInPixel);
      const clickedDepth = pointInGrid[1];

      // 2. 遍历完整数据源，找到深度上最近的数据行
      let closestPointData = null;
      let minDepthDistance = Infinity;
      this.echartsData.forEach(item => {
        const distance = Math.abs(item.depth - clickedDepth);
        if (distance < minDepthDistance) {
          minDepthDistance = distance;
          closestPointData = item;
        }
      });

      if (!closestPointData) return;

      let targetSeriesName = '';

      // 3. 判断目标曲线
      if (seriesNames.length === 1) {
        // 如果这个图表只有一条曲线，那目标就是它
        targetSeriesName = seriesNames[0];
      } else {
        // 如果有多条曲线（如图表4），我们再计算横向距离来找出最近的那条
        let minHorizontalDistance = Infinity;
        seriesNames.forEach(name => {
          const value = closestPointData[name];
          if (value === null || value === undefined) return;
          const pointPixel = chartInstance.convertToPixel('grid', [value, closestPointData.depth]);
          const horizontalDistance = Math.abs(pointInPixel[0] - pointPixel[0]);
          if (horizontalDistance < minHorizontalDistance) {
            minHorizontalDistance = horizontalDistance;
            targetSeriesName = name;
          }
        });
      }

      if (targetSeriesName) {
        console.log(`点击了 ${chartInstance.id.replace('-zr', '')}，已吸附到深度 ${closestPointData.depth}，目标曲线为: ${targetSeriesName}`);

        const currentOption = chartInstance.getOption();
        // ECharts 会在 option.legend[0].selected 中记录每个图例的选中状态
        // 如果 series 对应的图例值为 false，说明它在图表上被隐藏了
        if (currentOption.legend[0].selected[targetSeriesName] === false) {
          console.log(`曲线 ${targetSeriesName} 已通过图例隐藏，本次点击不触发弹窗。`);
          // 中断后续所有操作，不弹出对话框
          return;
        }

        // 4. (视觉反馈) 触发所有图表的 axisPointer
        const allCharts = [this.chart1, this.chart2, this.chart3, this.chart4];
        allCharts.forEach(chart => {
          chart.dispatchAction({
            type: 'updateAxisPointer',
            yAxisValue: closestPointData.depth
          });
        });

        // 5. (功能实现) 弹出对话框
        this.openEditDialog(closestPointData, targetSeriesName);
      }
    },
    // 将弹窗逻辑封装成独立方法，方便复用
    openEditDialog(pointData, seriesName) {
      console.log("pointData:", pointData);
      console.log("seriesName:", seriesName);
      const pointId = pointData.id;
      const depth = pointData.depth;
      // 从完整数据点中获取要修改的当前值
      const currentValue = pointData[seriesName];

      if (pointId === undefined) {
        console.warn('最近点没有ID，无法编辑。');
        return;
      }

      this.$prompt(`正在修改系列 "${seriesName.toUpperCase()}" 在深度 ${depth}m 处的数据点`, '修改数据', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: currentValue,
        inputValidator: (value) => { /* ... 校验逻辑 ... */
        }
      }).then(({value}) => {
        // ... 您原有的 API 请求和刷新逻辑 ...
        const updatePayload = {
          id: pointId,
          field: seriesName,
          value: Number(value)
        };
        console.log("穿过去的数据", updatePayload);
        this.$message.success('修改成功');
        this.retrieveEchartsData3();
        //发起后端请求
        // api.post('/kxyl/updateById', updatePayload).then(() => {
        //   this.$message.success('数据点更新成功!');
        //   this.retrieveEchartsData1();
        // }).catch(error => {
        //   this.$message.error('更新失败，请重试。');
        // });

      }).catch(() => {
        this.$message.info('已取消修改');
      });
    },
    async saveAsLongImage() {
      if (!this.map.well_id) {
        this.$message.error('请先选择井号');
        return;
      }

      const verticalZoomFactor = 1.5;
      this.isCapturing = true;

      const captureElement = document.getElementById('capture-area');
      if (!captureElement) {
        this.$message.error('无法找到捕获区域!');
        this.isCapturing = false;
        return;
      }

      const loading = this.$loading({
        lock: true,
        text: '正在生成高清长图，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      const chartContainers = document.querySelectorAll('.chart-container');
      const charts = [this.chart0, this.chart1, this.chart2, this.chart3, this.chart4];
      const originalHeight = chartContainers[0].style.height;

      this.originalDataZoomState = null; // 先重置
      if (this.chart1) {
        const options = this.chart1.getOption();
        if (options.dataZoom && options.dataZoom.length > 0) {
          this.originalDataZoomState = options.dataZoom[0];
        }
      }

      try {
        // 1. 根据“缩放系数”计算新的“长图”高度
        const yAxisOption = this.chart1.getOption().yAxis[0];
        const minDepth = yAxisOption.min;
        const maxDepth = yAxisOption.max;

        // 使用我们定义的缩放系数来计算最终高度
        const newHeight = (maxDepth - minDepth) * verticalZoomFactor;

        if (newHeight <= 0 || !isFinite(newHeight)) {
          this.$message.error('无法计算图表高度，请检查数据范围。');
          loading.close();
          return;
        }

        // 2. 应用新高度，让图表容器“变长”
        chartContainers.forEach(container => {
          container.style.height = `${newHeight}px`;
        });

        // 3. 重置ECharts尺寸并临时禁用dataZoom让其完全展开
        charts.forEach(chart => {
          if (chart) {
            chart.setOption({dataZoom: []}); // 禁用内部滚动
            chart.resize(); // 应用新的容器尺寸
          }
        });

        // 4. 等待DOM和ECharts重绘
        await new Promise(resolve => setTimeout(resolve, 1000));

        // 5. 执行长图截取
        const canvas = await html2canvas(captureElement, {
          scale: 2,
          useCORS: true,
          backgroundColor: '#ffffff',
          height: captureElement.scrollHeight,
          windowHeight: captureElement.scrollHeight,
        });

        // 6. 下载图片
        const image = canvas.toDataURL('image/png', 1.0);
        const link = document.createElement('a');
        link.href = image;
        link.download = `Bowers压力监测长图.png`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        this.$message.success('高清长图已成功保存！');

      } catch (error) {
        console.error('生成长图时出错:', error);
        this.$message.error('生成长图失败，请查看控制台。');
      } finally {
        // 7. 恢复原始状态
        chartContainers.forEach(container => {
          container.style.height = originalHeight;
        });

        // 將保存的單一 dataZoom 狀態應用於所有圖表
        charts.forEach(chart => {
          if (chart) {
            if (this.originalDataZoomState) {
              chart.setOption({
                dataZoom: [this.originalDataZoomState]
              });
            } else {
              chart.setOption({dataZoom: []});
            }
            chart.resize();
          }
        });
        this.isCapturing = false;
        loading.close();
      }
    },
    async exportReport() {
      this.isCapturing = true;
      const captureElement = document.getElementById('capture-area');
      if (!captureElement) {
        this.$message.error('无法找到捕获区域!');
        this.isCapturing = false;
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: '正在生成报告...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      await this.$nextTick(); // 确保 DOM 更新完成
      // 等待DOM和ECharts重绘
      await new Promise(resolve => setTimeout(resolve, 300));
      //先截图传给后端
      const canvas = await html2canvas(captureElement, {
        scale: 2,
        useCORS: true,
        backgroundColor: '#ffffff',
        height: captureElement.clientHeight + 80,
        windowHeight: captureElement.clientHeight + 80,
      });
      canvas.toBlob(async (blob) => {
        // 3. 封装成 FormData
        const fd = new FormData();
        fd.append('image', blob, 'screenshot.png'); // 文件名随意

        // 检查well_id是否存在
        if (!this.map.well_id) {
          this.$message.error('请先选择井');
          this.isCapturing = false;
          loading.close();
          return;
        }
        //获得父类的wellId
        fd.append("well_id", this.map.well_id);

        //上传
        api.post('/export/exportReportEaton', fd, {responseType: 'blob'}).then(res => {
          // 浏览器下载
          const blob = new Blob([res.data]);
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = `井报告.docx`;
          link.click();
          window.URL.revokeObjectURL(url);

          this.$message.success('导出成功');
        }).catch(err => {
          console.error('导出失败:', err);
          this.$message.error('导出失败', err.message);
        })

        this.isCapturing = false;
        loading.close();
      })
    }
  }
}
</script>

<style lang="css" scoped>
.pmjl-container {
  width: 100%;
  overflow: hidden;
  padding: 0 3rem;
}

.pmjl-table {
  border-collapse: collapse;
  width: 100%;
}

.tr-chart td {
  padding: 0;
}

.chart-container {
  height: calc(100vh - 200px);
  min-height: 600px;
  width: 100%;
}

.pull-left {
  float: left;
  top: 0
}

.pull-right {
  float: right;
  top: 0
}

.c-red {
  color: red;
}

.both-clear {
  clear: both;
  height: 1.25rem;
  line-height: 1.25rem;
}

.style-editor-button {
  position: fixed; /* 或者 absolute, 取决于你的布局 */
  top: 100px;
  right: 20px;
  z-index: 200;
}

.drawer-body {
  padding: 0 20px;
  height: calc(100vh - 120px); /* 减去头部和脚部高度 */
  overflow-y: auto;
}

.drawer-footer {
  padding: 10px 20px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  text-align: right;
}

.style-config-row {
  display: flex;
  align-items: center;
}

.style-config-item {
  margin-right: 15px;
}

.save-image-button {
  position: fixed;
  top: 160px;
  right: 20px;
  z-index: 200;
}

.export-report-button {
  position: fixed;
  top: 220px;
  right: 20px;
  z-index: 200;
}
</style>